package com.findyou.advice;

import com.findyou.utils.ConnectionUtils;
import com.findyou.utils.TransactionManager;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.SQLException;

/**
 * @Title: MyAdvice
 * @Author 贾金博
 * @Package com.findyou.advice
 * @Date 2024/12/6 上午9:19
 * @description: 增强类
 */
@Aspect
@Component
public class MyAdvice {

    @Autowired
    private TransactionManager transactionManager;


    // 把表达式给抽取出来
    @Pointcut("execution(public * com.findyou.service.Impl.AccountServiceImpl.* (..))")
    public void myPointCut() {
    }

    @Before("MyAdvice.myPointCut()")
    public void before() {
        System.out.println("this is before");
    }

    @Around("MyAdvice.myPointCut()") // 是非常灵活的
    public Object  around(ProceedingJoinPoint pjp) {
        Object object = null;
        System.out.println("this is around");
        // 执行正常操作
        try {
            // 开启手动提交
            transactionManager.beginTransaction();
            object = pjp.proceed();
            transactionManager.commit();
            System.out.println("commit successfully");
        } catch (Throwable e) {
            e.printStackTrace();
            transactionManager.rollback();
        }finally {
            transactionManager.release();
        }
        return object;
    }

}
